package com.ruoyi.api.controller;

import com.ruoyi.api.domain.InvestorReport;
import com.ruoyi.api.service.IInvestorReportService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author 寻觅
 * @since 2025-07-02
 */
@RestController
@RequestMapping("/investor-report")
public class InvestorReportController {

    @Autowired
    IInvestorReportService iInvestorReportService;

    @PostMapping("/file/add") // 建议使用POST上传文件
    public AjaxResult fileAdd(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }

            // 保存上传的文件到临时位置
            File tempFile = File.createTempFile("investor-report", ".pdf");
            file.transferTo(tempFile);

            // 处理文件并返回结果
            List<InvestorReport> reports = extractAllPages(tempFile.getAbsolutePath());
            iInvestorReportService.saveBatch(reports);
            // 删除临时文件
            tempFile.delete();

            return AjaxResult.success(reports);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("处理文件失败: " + e.getMessage());
        }
    }

    public List<InvestorReport> extractAllPages(String pdfPath) throws Exception {
        PDFTextStripperByArea regionStripper = new PDFTextStripperByArea();
        regionStripper.setSortByPosition(true);

        // 定义区域坐标
        regionStripper.addRegion("investorId", new Rectangle2D.Float(100, 240, 270, 10));
        regionStripper.addRegion("investorName", new Rectangle2D.Float(100, 250, 270, 10));
        regionStripper.addRegion("explain", new Rectangle2D.Float(10, 290, 270, 10));
        regionStripper.addRegion("endDate", new Rectangle2D.Float(137, 379, 90, 13));
        regionStripper.addRegion("units", new Rectangle2D.Float(256, 379, 90, 13));
        regionStripper.addRegion("nav", new Rectangle2D.Float(335, 379, 90, 13));
        regionStripper.addRegion("marketValue", new Rectangle2D.Float(495, 379, 90, 13));
        regionStripper.addRegion("valueChangePct", new Rectangle2D.Float(504, 392, 80, 13));
        regionStripper.addRegion("email", new Rectangle2D.Float(390, 130, 133, 15));

        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            int pageCount = document.getNumberOfPages();
            List<InvestorReport> investorReports = new ArrayList<>();

            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);

            for (int i = 0; i < pageCount; i++) {
                regionStripper.extractRegions(document.getPage(i));

                String investorId = cleanText(regionStripper.getTextForRegion("investorId"));
                String investorName = cleanText(regionStripper.getTextForRegion("investorName"));
                String explain = cleanText(regionStripper.getTextForRegion("explain"));
                String endDateStr = cleanText(regionStripper.getTextForRegion("endDate"));
                String units = cleanText(regionStripper.getTextForRegion("units"));
                String nav = cleanText(regionStripper.getTextForRegion("nav"));
                String marketValue = cleanText(regionStripper.getTextForRegion("marketValue"));
                String valueChangePct = cleanText(regionStripper.getTextForRegion("valueChangePct"));
                String email = cleanText(regionStripper.getTextForRegion("email"));

                LocalDate endDate = null;
                endDate = LocalDate.parse(endDateStr, dateFormatter);
                InvestorReport report = new InvestorReport();
                report.setInvestorId(investorId);
                report.setInvestorName(investorName);
                report.setExplainDescribe(explain);
                report.setEndDate(endDate);
                report.setUnits(units);
                report.setNav(nav);
                report.setMarketValue(marketValue);
                report.setValueChangePct(valueChangePct);
                report.setEmail(email);

                investorReports.add(report);
            }

            return investorReports;
        }
    }

    private String cleanText(String text) {
        if (text == null) return "";
        return text.trim().replaceAll("\\s+", " ");
    }
}
